package com.xinchao.job.service;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.mail.MessagingException;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xinchao.common.constant.BusinessConstant;
import com.xinchao.common.dto.DeviceMachineNumberDuplicateDTO;
import com.xinchao.common.model.WarnLog;
import com.xinchao.common.sms.SmsTemplateType;
import com.xinchao.common.util.EmailUtil;
import com.xinchao.common.util.HuaWeiSmsUtil;
import com.xinchao.job.mapper.dmp.DeviceInfoMapper;
import com.xinchao.job.mapper.dmp.DeviceSimInfoMapper;
import com.xinchao.job.mapper.dmp.DeviceWarnLogMapper;

@Service("deviceDuplicatePropCheckJobService")
public class DeviceDuplicatePropCheckJobService {
	private static Logger logger = LoggerFactory.getLogger(DeviceDuplicatePropCheckJobService.class);
	@Autowired
	private DeviceInfoMapper deviceInfoMapper;
	@Autowired
	private DeviceSimInfoMapper deviceSimInfoMapper;
	@Value("${xc.sms.huawei.callback.url}")
    private String sendStatusCallBackUrl;
	@Autowired
	private DeviceWarnLogMapper deviceWarnLogMapper;
	public void check() {
		
		// 清空离线且重复的sim信息
		// 如：设备a,b都对应了同一个imsi的上网卡,a离线则重置a的上网卡信息
		List<String> duplicateRecords = deviceSimInfoMapper.getDuplicateRecord();
		if ( CollectionUtils.isNotEmpty(duplicateRecords) ) {
			deviceSimInfoMapper.resetDuplicateRecord(duplicateRecords);
		}
		
		// 查询deviceNum重复的记录，给对应的管理人员发送提醒短信
		//duplicateMachineNumberRecordsHandler();
		
	}
	
	private void duplicateMachineNumberRecordsHandler() {
		List<DeviceMachineNumberDuplicateDTO> duplicateRecords = deviceInfoMapper.findDuplicateMachineNumberRecord();
		logger.warn(">> >> 处理重复机器码："+ JSON.toJSONString(duplicateRecords));
		duplicateRecordsHandler(duplicateRecords);
		
	}

	private void duplicateRecordsHandler( List<DeviceMachineNumberDuplicateDTO> duplicateRecords ) {
		if ( CollectionUtils.isNotEmpty(duplicateRecords) ) {
			for ( DeviceMachineNumberDuplicateDTO record : duplicateRecords ) {
				String tipMsg = String.format(BusinessConstant.DEVICE_NUM_DUMPLICATE_TIPS, record.getDeviceNum());
				if ( StringUtils.isNotBlank(record.getMobile()) ) {
					String[] params = { record.getDeviceNum()};
					
					// 发送短信
					Map<String, Object> returnMap = HuaWeiSmsUtil.sendSMS(SmsTemplateType.DEVICE_NUM_DUMPLICATE.getTemplateId(), JSONObject.toJSONString(params), record.getMobile(), sendStatusCallBackUrl);
					WarnLog warnLog = new WarnLog(record.getDeviceCode(), record.getAdministrator(), record.getMobile(), null, tipMsg, System.currentTimeMillis(), 
							BusinessConstant.TIPS_TYPE_DEVICE_NUM_DUMPLICATE, record.getCity(),BusinessConstant.SEND_STATUS_FAILURE,returnMap.get("smsMsgId").toString());
					
					// 保存发送记录
					deviceWarnLogMapper.insertWarnLog(warnLog);
				}
				if ( StringUtils.isNotBlank(record.getEmail()) ) {
					Integer sendFlag = BusinessConstant.SEND_STATUS_FAILURE;
					
					// 发送邮件
					try {
						EmailUtil.sendMail(tipMsg, "点位信息重复通知", record.getEmail());
					} catch (MessagingException | IOException e) {
						logger.error(e.getMessage(),e);
						e.printStackTrace();
					}
					sendFlag = BusinessConstant.SEND_STATUS_SUCCESS;
					WarnLog warnLog = new WarnLog(record.getDeviceCode(), record.getAdministrator(), null, record.getEmail(), tipMsg, System.currentTimeMillis(), 
							BusinessConstant.TIPS_TYPE_DEVICE_NUM_DUMPLICATE, record.getCity(),sendFlag);
					
					// 保存发送记录
					deviceWarnLogMapper.insertWarnLog(warnLog);
				}
			}
		}
	}
}
